import NProgress from "nprogress";
import "nprogress/nprogress.css";
import router from "@/router";
import { getToken } from "./utils/token";
import store from "@/store";
import nProgress from "nprogress";

// 免登录白名单路由
const whiteList = ["/login"];

router.beforeEach((to, from, next) => {
  nProgress.start();
  const token = getToken();
  const toPath = to.path;
  if (token) {
    // 登录禁止去登录页
    if (toPath === "/login") {
      next("/");
      return;
    }
    const username = store.state.user.loginUser.username;
    if (!username) {
      // 获取用户信息
      try {
        store.dispatch("user/getLoginUserInfo").then(() => {
          next();
        });
      } catch {
        next(`/login?redirect=${to.fullPath}`);
      }
    } else {
      next();
    }
  } else {
    if (whiteList.includes(toPath)) {
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
